<template>
	<el-dialog :close-on-click-modal="false" :title="`${mode === 'add' ? '新增' : mode === 'edit' ? '修改' : '查看'}作业记录`" width="500px" v-model="visible" @confirm="confirm"
		@cancel="visible = false" @close="closeDialog">
		<div class="formData">
			<el-form :model="formData" ref="ruleForm" label-width="120px" :rules="rules">
				<el-form-item label="拖轮" prop="tugId">
				  <Select placeholder="请选择拖轮" :selectData="selects.tugList" v-model:value="formData.tugId" v-model:label="formData.tugNo" disabled />
				</el-form-item>
				<el-form-item label="作业项目" prop="workItemId">
				  <Select placeholder="请选择作业项目" :selectData="selects.workItemList" v-model:value="formData.workItemId" v-model:label="formData.workItemName" disabled />
				</el-form-item>
				<el-form-item label="开始作业时间" prop="beginTime">
				  <el-date-picker v-model="formData.beginTime" value-format="YYYY-MM-DD HH:mm:ss" type="datetime" placeholder="请选择开始作业时间" :disabled="mode == 'view'" />
				</el-form-item>
				<el-form-item label="结束作业时间" prop="endTime">
				  <el-date-picker v-model="formData.endTime" value-format="YYYY-MM-DD HH:mm:ss" type="datetime" placeholder="请选择结束作业时间" :disabled="mode == 'view'" />
				</el-form-item>
				<!-- <el-form-item label="油耗" prop="oilConsume">
				  <el-input v-model="formData.oilConsume" placeholder="请输入油耗(L)" :disabled="mode == 'view'"></el-input>
				</el-form-item>
				<el-form-item label="行驶里程" prop="distance">
				  <el-input v-model="formData.distance" placeholder="请输入行驶里程" :disabled="mode == 'view'"></el-input>
				</el-form-item> -->
				<el-form-item label="附件" prop="attachList">
					<el-image
						  class="filesClass"
						  :src="item"
						  :zoom-rate="1.2"
						  :max-scale="7"
						  :min-scale="0.2"
						  :preview-src-list="attachList"
						  :initial-index="index"
						  fit="cover"
						  v-if="mode == 'view'"
						  v-for="(item,index) in attachList" :key="index"
						/>
					<upload businessType="PORD_WORK_FINISH_WORK" businessId="" :fileList1="attachList" @changeFile="changeFile" fileTypeName=".jpeg, .png, .jpg" v-else />
				</el-form-item>
			</el-form>
		</div>
		<template #footer>
			<div class="dialog-footer">
				<el-button @click="closeDialog">取消</el-button>
				<el-button type="primary" @click="confirm">
					确认
				</el-button>
			</div>
		</template>
	</el-dialog>
</template>

<script setup>
	import {
		ref,
		onMounted,
		reactive,
		defineEmits,
		defineExpose,
		nextTick
	} from "vue";
	import {
		ElMessage,
		ElMessageBox,
		ElNotification
	} from "element-plus";
import Select from '@/components/Select/index.vue'
	import RemoteSelect from '@/components/RemoteSelect/index.vue';
import tugApi from '@/api/basicData/tug';
import recordApi from '@/api/plan/plan/recordIndex'
import api from '@/api/plan/plan/index';
import workItemApi from '@/api/basicData/workItem';
import upload from '@/components/upload.vue';
import publicApi from '@/api/public'
	const emit = defineEmits(['callback'])
const attachList = ref([])
	const selects = ref({
		tugList:[],
		workItemList:[]
	})

	const visible = ref(false)
	const mode = ref('add')
	const row = ref({})
	const fileList = ref([])
	const formData = ref({
      tugId: '',
      tugNo: '',
	  beginTime:'',
	  endTime:'',
      workItemId: '',
      workItemName: '',
	  planId:'',
	  oilConsume:'',
	  distance:'',
	  attachList:[]
    })
	const ruleForm = ref({})
const validateAmount = (rule, value, callback) => {
		if (!value) {
			return callback()
		}
		// 使用正则表达式校验小数点后是否只有两位  
		if (!/^-?\d+(\.\d{1,2})?$/.test(value)) {
			callback(new Error('请输入数字'));
		} else {
			// 注意：这里可能还需要进一步处理，确保末尾不是".00"之类的，但为简化示例，暂不处理  
			callback();
		}
	}
	const rules = ref({
		tugId: [{
			required: true,
			message: '不能为空',
			trigger: 'blur'
		}],
		workItemId: [{
			required: true,
			message: '不能为空',
			trigger: 'blur'
		}],
		beginTime: [{
			required: true,
			message: '不能为空',
			trigger: 'blur'
		}],
		endTime: [{
			required: true,
			message: '不能为空',
			trigger: 'blur'
		}],
		/* attachList: [{
			required: true,
			message: '不能为空',
			trigger: 'blur'
		}], */
		oilConsume: [{
			validator: validateAmount,
			trigger: 'blur'
		}],
		distance: [{
			validator: validateAmount,
			trigger: 'blur'
		}],
	})
	// 文件上传
	const changeFile = file => {
		console.log(file);
		formData.value.attachList = file
	}
	// 展示
	const show = params => {
		visible.value = true
		mode.value = params?.mode || 'add'
		row.value = params.row;
		editInit();
		getSelectList()
	}
	// 编辑
	const editInit = async () => {
		var files = []
		recordApi.getDetailById({id:row.value.id}).then(res=>{
			  //判断是否存在文件
			  if (res.data.attachList.length > 0) {
			  	res.data.attachList.forEach(item => {
			  		files.push({
			  			id: item.fileId,
			  			fileSuffix: item.url.substring(item.url.lastIndexOf('.'), item.url
			  				.length),
			  			fileName: item.url.substring(item.url.lastIndexOf('/') + 1, item.url
			  				.length)
			  		})
			  	})
			  }
			  formData.value = res.data;
		}).then(_=>{
			  formData.value.attachList = files.map(v => v.id)
			  attachList.value = files;
		}).then(_=>{
			  if(mode.value == 'view'){
				  attachList.value = []
				  formData.value.attachList.forEach(item=>{
					  publicApi.down(item, 'arraybuffer').then(res => {
					    const blob = new Blob([res.data], {
					      type: 'application/png;charset=utf-8'
					    })
					    attachList.value.push(window.URL.createObjectURL(blob))
					  })
				  })
			  }
		})
	}
	// 确认
	const confirm = () => {
		ruleForm.value.validate(valid => {
			if (valid) {
				let request;
				if(mode.value === 'add'){
				  delete formData.value.id;
				}
				api.amountV2([formData.value]).then(res => {
				  if (res.code == '200') {
				    ElMessage.success('保存成功')
				    visible.value = false;
				    emit("callback");
				  } else {
				    ElMessage.error(res.msg)
				  }
				})
			} else {
				ElMessage.warning('请完善表单信息！')
			}
		})
	}

	// 重置
	const closeDialog = () => {
		nextTick(() => {
			visible.value = false
			ruleForm.value.resetFields()
		})
	}
	defineExpose({
		show
	})
	const getSelectList = () => {
		selects.value.tugList = []
		selects.value.workItemList = []
		tugApi.getList({startPage:1,pageSize:100}).then(res=>{
			if(res.data.records.length > 0){
				res.data.records.forEach(item=>{
					selects.value.tugList.push({label:item.tugNo,value:item.id})
				})
			}
		})
		workItemApi.getList({startPage:1,pageSize:100,workTypeCode:1}).then(res=>{
			
				if(res.data.records.length > 0){
					res.data.records.forEach(item=>{
						selects.value.workItemList.push({label:item.workItem,value:item.id})
					})
				}
		})
	}
</script>
<style>
	.filesClass{
		display: inline-block;width: 100px; height: 100px;margin: 0 10px 10px 0;
	}
	.filesClass:nth-child(3n){
		margin-right: 0;
	}
</style>